﻿using System.Collections.Generic;
using HCQ2_Model;
using HCQ2_Model.DocModel;
using System.Linq;
using System;
using HCQ2_Model.TreeModel;
using HCQ2_Model.DocModel.APIModel;
using System.Web;
using HCQ2_Model.DocModel.APIResultModel;
using HCQ2_Model.VR.Model;
using HCQ2_Model.VR.Params;
using HCQ2_Model.VLine.Params;
using HCQ2_Model.VLine.InputDto;
using HCQ2_Common;
using HCQ2_Model.VRDD.OutputDto._0730;
using HCQ2_Model.VRQDMeta.OutputDto._20220418;
using HCQ2_Model.VRQDMeta.InputDto._20220418;

namespace HCQ2_BLL
{
    public partial class T_DocumentFolderBLL:HCQ2_IBLL.IT_DocumentFolderBLL
    {
        private List<DocTreeListModel> docList = new List<DocTreeListModel>();
        private List<DocTreeListModel> docTempList = new List<DocTreeListModel>();
        /// <summary>
        ///  数组格式返回数据
        /// </summary>
        private List<DocTreeModel> listTreeModel = new List<DocTreeModel>();
        private List<VRClientTreeModel> listVRTreeModel = new List<VRClientTreeModel>();
        private bool isCount = true;

        #region 获取第一层数据 T_DocumentGoodFolder
        /// <summary>
        ///  获取第一层数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="inColud">无父是否显示子</param>
        /// <returns></returns>
        private List<T_DocumentGoodFolder>GetFirstTreeData(List<T_DocumentGoodFolder> list,bool inColud)
        {
            List<T_DocumentGoodFolder> treeList = new List<T_DocumentGoodFolder>();
            if (list == null || list.Count <= 0)
                return null;
            treeList = list.FindAll(s => s.folder_pid == 0)?.OrderByDescending(s=>s.folder_order)?.ToList();
            //添加目录无权限时、是目录有权限添加进去
            if (inColud)
            {
                list.ForEach(o =>
                {
                    var obj = GetSecondTreeData(list, o, o.folder_pid);
                    if (obj.folder_pid != 0)
                    {
                        var ss = treeList.Where(s => s.folder_id == obj.folder_id);
                        if (ss == null || ss.Count() <= 0)
                            treeList.Add(obj);
                    }
                });
            }
            return treeList;
        }
        private T_DocumentGoodFolder GetSecondTreeData(List<T_DocumentGoodFolder> list, T_DocumentGoodFolder folder, int folder_pid)
        {
            var query = list.Where(o => o.folder_id == folder_pid)?.FirstOrDefault();
            if (query != null)
               return GetSecondTreeData(list, query, query.folder_pid);
            return folder;
        }
        #endregion

        #region 获取第一层数据 T_DocumentFolder
        /// <summary>
        ///  获取第一层数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private List<T_DocumentFolder> GetFirstTreeData(List<T_DocumentFolder> list)
        {
            List<T_DocumentFolder> treeList = new List<T_DocumentFolder>();
            if (list == null || list.Count <= 0)
                return null;
            treeList = list.FindAll(s => s.folder_pid == 0);
            list.ForEach(o =>
            {
                var obj = GetSecondTreeData(list, o, o.folder_pid);
                if (obj.folder_pid != 0)
                {
                    var ss = treeList.Where(s => s.folder_id == obj.folder_id);
                    if(ss == null || ss.Count() <= 0)
                        treeList.Add(obj);
                }
            });
            return treeList;
        }
        private T_DocumentFolder GetSecondTreeData(List<T_DocumentFolder> list, T_DocumentFolder folder, int folder_pid)
        {
            var query = list.Where(o => o.folder_id == folder_pid)?.FirstOrDefault();
            if (query != null)
               return GetSecondTreeData(list, query, query.folder_pid);
            return folder;
        }
        #endregion

        /// <summary>
        ///  根据用户获取文档结构树
        ///  VRPPT：1
        ///  创客：2
        ///  头记：3
        ///  校史馆：4
        /// </summary>
        /// <param name="pro_type">产品类型</param>
        /// <returns></returns>
        public List<DocTreeModel> GetDocTreeData(int pro_type,int isNum, bool notType = false, string folder_path = "", int vrType = 0)
        {
            //1.获取当前用户权限集合
            List<T_Permissions> PerList = HCQ2UI_Helper.Session.SysPermissSession.PermissList;
            List<int> pList = new List<int>();
            if (PerList != null && PerList.Count > 0)
                pList = PerList.Select(s => s.per_id).ToList();
            List<T_DocumentFolder> list = DBSession.IT_DocumentFolderDAL.GetDocTreeData(HCQ2UI_Helper.OperateContext.Current.Usr.user_id, pro_type, pList, false, folder_path)?.OrderByDescending(s => s.folder_order)?.ToList();
            if (null == list || list.Count <= 0)
                return null;
            List<DocTreeModel> listModel = new List<DocTreeModel>();
            foreach(var item in list)
            {
                string folderName = item.folder_name;
                int total = 0;
                if (isNum<=0)
                    total = DBSession.IT_DocumentInfoDAL.GetProDocCount(item.folder_path,notType);//获取节点下文档数量
                if (total > 0)
                    folderName = folderName + "(" + total + ")";
                //语言库对应翻译
                var foldeName = LangHelper.GetValue("NavigationFolder." + item.langCode);
                var parent = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == item.folder_pid);
                listModel.Add(new DocTreeModel()
                {
                    id = item.folder_id,
                    name = (!string.IsNullOrEmpty(foldeName) && !foldeName.Equals("null")) ? foldeName : item.folder_name,
                    enLang = (!isChinese) ? folderName : item.enLang,
                    langCode = item.langCode,
                    pId = item.folder_pid,
                    pName = parent?.folder_name,
                    pPath=parent?.folder_path,
                    materType = item.mater_type,
                    if_create_child = item.if_create_child,
                    read_only = item.read_only,
                    was_share = item.was_share,
                    if_sys = item.if_sys,
                    folder_path = item.folder_path,
                    doc_type = item.doc_type,
                    is_recommend = item.is_recommend,
                    re_folder = item.is_recommend ? 1 : 0,
                    //rest_type = item.rest_type,
                    folder_note = item.folder_note,
                    pro_type = item.pro_type,
                    unit_code = item.unit_code,
                    group_name = item.group_name,
                    folder_order = (item.folder_order != null) ? (int)item.folder_order : 0,
                    if_private = item.if_private,
                    if_limit = item.if_limit,
                    is_share = item.is_share ? 1 : 0,
                    founder_name = item.founder_name,
                });
            }
            return listModel;
        }
        /// <summary>
        ///  根据用户权限获取文档结构树
        ///  isApprove ：是否是审核界面，审核时需要排除私有目录
        ///  folder_path：需要被排除的path
        /// </summary>
        /// <returns></returns>
        public List<DocTreeModel> GetDocTreeData(string pageType,int doc_type, int isNum, bool notType = false,bool isApprove=false, string folder_path = "", int vrType = 0)
        {
            if (isNum > 0)
                isCount = false;
            //1.获取当前用户权限集合
            List<T_Permissions> PerList = HCQ2UI_Helper.Session.SysPermissSession.PermissList;
            List<int> pList = new List<int>();
            if(PerList != null && PerList.Count > 0)
                pList = PerList.Select(s => s.per_id).ToList();
            bool isPrivate = (doc_type != 3 && doc_type !=4) ? true : false;//私有：true=无，false=有
            List<T_DocumentFolder> list = DBSession.IT_DocumentFolderDAL.GetDocTreeData(HCQ2UI_Helper.OperateContext.Current.Usr.user_id, pageType, pList, isPrivate, isApprove, folder_path,doc_type);
            if (null == list || list.Count <= 0)
                return null;
            List<DocTreeModel> listModel = new List<DocTreeModel>();
            #region 1. 一级目录
            List<T_DocumentFolder> temp = GetFirstTreeData(list)?.OrderByDescending(s => s.folder_order)?.ToList();
            foreach (T_DocumentFolder item in temp)
            {
                var len = list.Where(s => s.folder_pid == item.folder_id).ToList();
                int total = GetFileInfoCount(doc_type, item.folder_id,item.folder_path,vrType);//获取节点下文档数量
                docList.Add(new DocTreeListModel { ply = 1, folder_id = item.folder_id, folder_pid = item.folder_pid, total = total, doc_type = doc_type });
                //语言库对应翻译
                var foldeName = LangHelper.GetValue("NavigationFolder." + item.langCode);
                T_DocumentFolder parent = new T_DocumentFolder();
                if(item.folder_pid>0)
                    parent = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == item.folder_pid);
                listModel.Add(new DocTreeModel()
                {
                    founder_id=item.founder_id,
                    founder_login=item.founder_login,
                    founder_name = item.founder_name,
                    id = item.folder_id,
                    ply = 1,
                    name = (!string.IsNullOrEmpty(foldeName) && !foldeName.Equals("null")) ? foldeName : item.folder_name,
                    enLang = (!isChinese) ? item.folder_name : item.enLang,
                    langCode = item.langCode,
                    pId = item.folder_pid,
                    pName = parent?.folder_name,
                    pPath = parent?.folder_path,
                    materType = item.mater_type,
                    if_create_child = item.if_create_child,
                    read_only = item.read_only,
                    was_share = item.was_share,
                    if_sys = item.if_sys,
                    folder_path = item.folder_path,
                    doc_type = item.doc_type,
                    is_recommend = item.is_recommend,
                    re_folder = item.is_recommend ? 1 : 0,
                    //rest_type = item.rest_type,
                    folder_note = item.folder_note,
                    pro_type = item.pro_type,
                    unit_code = item.unit_code,
                    folder_order = (item.folder_order != null) ? (int)item.folder_order : 0,
                    if_private = item.if_private,
                    if_limit = item.if_limit,
                    group_name = item.group_name,
                    is_share = item.is_share ? 1 : 0, 
                    gps_x=item.gps_x,
                    gps_y=item.gps_y,
                    bs_type=item.bs_type,
                    floor_level=item.floor_level,
                    city=item.city,
                    bs_url = item.bs_url,
                    addr=item.addr,
                    sortType=item.sortType,
                    statr_partner =item.statr_partner,
                    children = (len.Count > 0) ? GetModelById(list, item.folder_id, doc_type,vrType) : null
                });
            }
            #endregion

            if(!isCount)
                return listModel;

            #region 2.遍历更新docList
            if (null == docList || docList.Count <= 0)
                return listModel;
            var lTemp = docList.Where(s => s.ply == 1).ToList();
            foreach (DocTreeListModel item in lTemp)
            {
                int ownCount = item.total, childCount = 0, count;
                var child = docList.Where(s => s.folder_pid == item.folder_id).ToList();
                if (child.Count > 0)
                    childCount = GetFolderName(listModel, child, item.folder_id, doc_type);
                count = ownCount + childCount;
                if (count > 0)
                    listModel.Where(s => s.id == item.folder_id).FirstOrDefault().name += string.Format("({0})", count);
            }
            #endregion

            #region 3.更新二级目录及以下
            if (null == docTempList || docTempList.Count <= 0)
                return listModel;
            foreach (DocTreeModel item in listModel)
            {
                var obj = docTempList.Where(s => s.folder_id == item.id).FirstOrDefault();
                if (obj != null && obj.total>0)
                {
                    if (item.name.IndexOf("(") > -1)
                        item.name = item.name.Split('(')[0] + string.Format("({0})", obj.total);
                    else
                        item.name += string.Format("({0})", obj.total);
                }
                if (item.children != null)
                    SetFolderName(item.children);
            }
            #endregion
            return listModel;
        }
        /// <summary>
        ///  根据商品id获取目录信息
        /// </summary>
        /// <param name="file_id"></param>
        /// <returns></returns>
        public T_DocumentFolder GetFolderByFileId(int file_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetFolderByFileId(file_id);
        }


        #region APP接口
        /// <summary>
        ///  获取元宇宙素材目录导航
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<QDMaterialTreeOutput> GetQDMaterialTreeData(QDMaterialTreeInput param)
        {
            List<QDMaterialTreeOutput> result = new List<QDMaterialTreeOutput>();
            var list = DBSession.IT_DocumentFolderDAL.GetQDMaterialTreeData(param);
            if (param.dataFormat.ToLower().Equals("list"))
            {
                list?.ForEach(s => {
                    if (!string.IsNullOrEmpty(s.folderImage))
                        s.folderImage = s.folderImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    result.Add(Helper.AutoMapperConvert<QDMaterialTreeOutput, QDTreeOutput>(s));
                });
                return result;
            }
            //tree模式返回
            if (null == list || list.Count <= 0)
                return null;
            //找出最小id
            List<QDTreeOutput> treeList = list.FindAll(s => s.folderPid == 0)?.OrderByDescending(s => s.folderOrder)?.ToList();
            treeList = treeList == null ? new List<QDTreeOutput>() : treeList;
            //添加目录无权限时、是目录有权限添加进去
            list.ForEach(o =>
            {
                var obj = GetMaterSecondTreeData(list, o, o.folderPid);
                if (obj.folderPid != 0)
                {
                    var ss = treeList.Where(s => s.folderID == obj.folderID);
                    if (ss == null || ss.Count() <= 0)
                        treeList.Add(obj);
                }
            });
            if (treeList != null && treeList.Count > 0)
                treeList = treeList.OrderByDescending(s => s.folderOrder)?.ToList();
            //遍历一级目录
            treeList.ForEach(s =>
            {
                var temp = Helper.AutoMapperConvert<QDMaterialTreeOutput, QDTreeOutput>(s);
                if (!string.IsNullOrEmpty(temp.folderImage))
                    temp.folderImage = temp.folderImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                var len = list.Where(o => o.folderPid == temp.folderID)?.Count();
                if (null != len && len > 0)
                {                    
                    var childList= GetMaterChildTreeData(list, temp.folderID);
                    var child = new List<QDMaterialTreeOutput>();
                    childList?.ForEach(n => child.Add(Helper.AutoMapperConvert<QDMaterialTreeOutput, QDTreeOutput>(n)));
                    temp.children = child;
                }
                result.Add(temp);
            });
            return result;
        }
        /// <summary>
        ///  获取元宇宙城市目录导航
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<QDCityTreeOutput> GetQDCityTreeData(QDMaterialTreeInput param)
        {
            List<QDCityTreeOutput> result = new List<QDCityTreeOutput>();
            var list = DBSession.IT_DocumentFolderDAL.GetQDCityTreeData(param);
            if (param.dataFormat.ToLower().Equals("list"))
            {
                list?.ForEach(s => {
                    var images = DBSession.IT_DocBagFolderRecordDAL.Select(o => o.folder_id == s.folderID);
                    if (images != null && images.Count > 0)
                    {
                        //缩略图【横板4：3】folder_type=0
                        var _hb = images.Where(n => n.folder_type == 0)?.FirstOrDefault();
                        if (_hb != null && !string.IsNullOrEmpty(_hb.file_url))
                            s.folderImage = _hb.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                        //缩略图【竖板3：4】folder_type=1
                        var _sb = images.Where(n => n.folder_type == 1)?.FirstOrDefault();
                        if (_sb != null && !string.IsNullOrEmpty(_sb.file_url))
                            s.cityImage = _sb.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    }
                    result.Add(Helper.AutoMapperConvert<QDCityTreeOutput, QDTreeOutput>(s));
                });
                return result;
            }
            //tree模式返回
            if (null == list || list.Count <= 0)
                return null;
            //找出最小id
            List<QDTreeOutput> treeList = list.FindAll(s => s.folderPid == 0)?.OrderByDescending(s => s.folderOrder)?.ToList();
            treeList = treeList == null ? new List<QDTreeOutput>() : treeList;
            //添加目录无权限时、是目录有权限添加进去
            list.ForEach(o =>
            {
                var obj = GetMaterSecondTreeData(list, o, o.folderPid);
                if (obj.folderPid != 0)
                {
                    var ss = treeList.Where(s => s.folderID == obj.folderID);
                    if (ss == null || ss.Count() <= 0)
                        treeList.Add(obj);
                }
            });
            if (treeList != null && treeList.Count > 0)
                treeList = treeList.OrderByDescending(s => s.folderOrder)?.ToList();
            //遍历一级目录
            treeList.ForEach(s =>
            {
                var temp = Helper.AutoMapperConvert<QDCityTreeOutput, QDTreeOutput>(s);
                var images = DBSession.IT_DocBagFolderRecordDAL.Select(o => o.folder_id == s.folderID);
                if(images!=null && images.Count > 0)
                {
                    //缩略图【横板4：3】folder_type=0
                    var _hb = images.Where(n => n.folder_type == 0)?.FirstOrDefault();
                    if(_hb != null && !string.IsNullOrEmpty(_hb.file_url))
                        temp.folderImage= _hb.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    //缩略图【竖板3：4】folder_type=1
                    var _sb = images.Where(n => n.folder_type == 1)?.FirstOrDefault();
                    if (_sb != null && !string.IsNullOrEmpty(_sb.file_url))
                        temp.cityImage = _sb.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                }
                var len = list.Where(o => o.folderPid == temp.folderID)?.Count();
                if (null != len && len > 0)
                {
                    var childList = GetMaterChildTreeData(list, temp.folderID);
                    var child = new List<QDCityTreeOutput>();
                    childList?.ForEach(n => child.Add(Helper.AutoMapperConvert<QDCityTreeOutput, QDTreeOutput>(n)));
                    temp.children = child;
                }
                result.Add(temp);
            });
            return result;
        }


        private List<QDTreeOutput> GetMaterChildTreeData(List<QDTreeOutput> list,int folderId)
        {
            List<QDTreeOutput> obj = new List<QDTreeOutput>();
            var child = list.Where(s => s.folderPid == folderId)?.ToList();
            if (child != null && child.Count > 0)
                child = child.OrderByDescending(s => s.folderOrder)?.ToList();
            child?.ForEach(s =>
            {
                var images = DBSession.IT_DocBagFolderRecordDAL.Select(o => o.folder_id == s.folderID);
                if (images != null && images.Count > 0)
                {
                    //缩略图【横板4：3】folder_type=0
                    var _hb = images.Where(n => n.folder_type == 0)?.FirstOrDefault();
                    if (_hb != null && !string.IsNullOrEmpty(_hb.file_url))
                        s.folderImage = _hb.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    //缩略图【竖板3：4】folder_type=1
                    var _sb = images.Where(n => n.folder_type == 1)?.FirstOrDefault();
                    if (_sb != null && !string.IsNullOrEmpty(_sb.file_url))
                        s.cityImage = _sb.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                }
                var len = list.Where(o => o.folderPid == s.folderID)?.Count();
                if (null != len && len > 0)
                    s.children = GetMaterChildTreeData(list, s.folderID);
                obj.Add(s);
            });
            return obj;
        }
        private QDTreeOutput GetMaterSecondTreeData(List<QDTreeOutput> list, QDTreeOutput folder, int folderPid)
        {
            var query = list.Where(o => o.folderID == folderPid)?.FirstOrDefault();
            if (query != null)
                return GetMaterSecondTreeData(list, query, query.folderPid);
            return folder;
        }
        /// <summary>
        ///  APP接口： 获取商城树
        /// </summary>
        /// <returns></returns>
        public List<VRClientTreeModel> GetDocTreeAPIData(EmpowerTree param,int user_id)
        {
            List<T_DocumentGoodFolder> list = null;
            List<int> pList = new List<int>();
            if (user_id > 0)
            {
                //1.获取当前用户权限集合
                List<T_Permissions> PerList = DBSession.IT_PermissionsDAL.GetPermissById(user_id);
                if (PerList != null && PerList.Count > 0)
                    pList = PerList.Select(s => s.per_id).ToList();
            }
            if(!param.limitType && param.treeScope!=0)
                user_id = 0;
            list = DBSession.IT_DocumentFolderDAL.GetDocTreeAPIData(param, user_id, pList);
            if (null == list || list.Count <= 0)
                return null;
            List<VRClientTreeModel> listModel = new List<VRClientTreeModel>();
            #region Tree 或者 List格式    
            bool inColud = false; //param.dataFormat.ToLower().Equals("list")
            if (!string.IsNullOrEmpty(param.roleCode) || !string.IsNullOrEmpty(param.folder_path) || param.dataFormat.Equals("tree"))
                inColud = true;
            List<T_DocumentGoodFolder> temp = null;
            if (param.dataFormat.Equals("list"))
                temp = list;
            else
                temp = GetFirstTreeData(list, inColud);
            if (temp != null && temp.Count > 0)
                temp = temp.OrderByDescending(s => s.folder_order)?.ToList();
            foreach (T_DocumentGoodFolder item in temp)
            {
                var len = list.Where(s => s.folder_pid == item.folder_id).ToList();
                VRClientTreeModel treeTemp = new VRClientTreeModel
                {
                    star_num=item.star_num,
                    focus_num=item.focus_num,
                    floor_level = item.floor_level,
                    city = item.city,
                    addr = item.addr,
                    statr_partner = item.statr_partner,
                    founder_phone = item.founder_phone,
                    sense = item.sense,
                    gps_x = item.gps_x,
                    gps_y = item.gps_y,
                    bs_type = item.bs_type,
                    bs_url = item.bs_url,
                    create_name = item.create_name,
                    create_date = item.create_time.ToString("yyyy-MM-dd HH:mm"),
                    update_name = item.update_name,
                    update_date = item.update_date.ToString("yyyy-MM-dd HH:mm"),
                    ply = item.levels,
                    learn_num = item.learn_num,
                    topic_num = item.topic_num,
                    result_ok = item.result_ok,
                    result_error = item.result_error,
                    id = item.folder_id,
                    is_recommend = item.is_recommend,
                    name = item.folder_name,
                    enLang = item.enLang,
                    pId = item.folder_pid,
                    read_only = item.read_only,
                    folder_path = item.folder_path,
                    folder_note = item.folder_note,
                    unit_code = item.unit_code,
                    folder_order = (item.folder_order != null) ? (int)item.folder_order : 0,
                    folder_url = (!string.IsNullOrEmpty(item.folder_url)) ? item.folder_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) : "",
                    pro_type = item.pro_type,
                    proType = item.proType,
                    if_private = item.if_private ? 1 : 0,
                    group_name = item.group_name,
                    is_share = item.is_share ? 1 : 0,
                    favorite = item.favorite,
                    isFavorite = item.favorite > 0 ? true : false,
                    founder_id = item.founder_id,
                    founder_name = item.founder_name
                };
                //合伙人协议
                var deal_note = DBSession.IT_VRFounderDealDAL.FindSingle(o => o.folder_id == item.folder_id);
                treeTemp.deal_note = deal_note?.deal_note;
                //判断用户是否点赞
                if (param.user > 0)
                {
                    int isStar = DBSession.IT_VRUserFolderStarDAL.SelectCount(s => s.user_guid.Equals(param.userid) && s.folder_id == item.folder_id);
                    treeTemp.isStar = isStar > 0;
                    //treeTemp.star_num = DBSession.IT_VRUserFolderStarDAL.SelectCount(s => s.folder_id == item.folder_id);
                    //int isFous = DBSession.IT_VRUserFolderDAL.SelectCount(s => s.folder_id == item.folder_id);
                    //treeTemp.focus_num = isFous > 0 ? isFous : 0;
                }
                int allCount = item.result_ok + item.result_error;
                if (item.result_error == 0 && allCount > 0)
                    treeTemp.accuracy = 100;
                else if (allCount > 0)
                {
                    var _result = float.Parse(item.result_ok.ToString()) / float.Parse((item.result_ok + item.result_error).ToString());
                    treeTemp.accuracy = (int)(Math.Round(_result, 2) * 100);
                }
                if (param.dataFormat.Equals("tree"))
                {
                    treeTemp.children = (len.Count > 0) ? GetAPPModelById(param,list, item.folder_id, 2) : null;
                    listVRTreeModel.Add(treeTemp);
                }
                else
                {
                    listVRTreeModel.Add(treeTemp);
                    if (len.Count > 0 && param.dataFormat.Equals("tree"))
                        GetAPPModelById(param, list, item.folder_id, 2, "list");
                }
            }
            if (param.dataFormat.Equals("tree"))
                return listVRTreeModel;
            else
                return listVRTreeModel.OrderBy(s => s.ply).ToList();
            #endregion
        }
        /// <summary>
        ///  获取目录路径列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<DocLevelTree> GetFolderPathList(DocLevelTreeParam model)
        {
            var list = DBSession.IT_DocumentFolderDAL.GetFolderPathList(model);
            list?.ForEach(s =>
            {
                if (!string.IsNullOrEmpty(s.folderImage))
                    s.folderImage = s.folderImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            });
            return list;
        }
        /// <summary>
        ///  获取商城树相关统计
        /// </summary>
        /// <returns></returns>
        public List<TreeDataStatisticsNode> GetTreeStatistics(EmpowerTree param, int user_id)
        {
            List<TreeDataStatistics> list = null;
            List<int> pList = new List<int>();
            if (param.proType != 3 && param.proType != 4 && user_id > 0)
            {
                //1.获取当前用户权限集合
                List<T_Permissions> PerList = DBSession.IT_PermissionsDAL.GetPermissById(user_id);
                if (PerList != null && PerList.Count > 0)
                    pList = PerList.Select(s => s.per_id).ToList();
            }
            else
                user_id = 0;
            list = DBSession.IT_DocumentFolderDAL.GetTreeStatisticsAPI(param, user_id, pList);
            if (null == list || list.Count <= 0)
                return null;
            List<TreeDataStatisticsNode> listModel = new List<TreeDataStatisticsNode>();
            #region 1. 一级目录      
            List<TreeDataStatistics> temp = list.FindAll(s => s.folder_pid == 0);
            foreach (TreeDataStatistics item in temp)
            {
                var len = list.Where(s => s.folder_pid == item.folder_id).ToList();
                TreeDataStatisticsNode obj = new TreeDataStatisticsNode
                {
                    folder_id = item.folder_id,
                    folder_pid = item.folder_pid,
                    learn_num = item.learn_num,
                    topic_num = item.topic_num,
                    result_ok = item.result_ok,
                    result_error = item.result_error
                };
                int allCount = item.result_ok + item.result_error;
                if (item.result_error == 0 && allCount > 0)
                    obj.accuracy = 100;
                else if (allCount > 0)
                {
                    var _result = float.Parse(item.result_ok.ToString()) / float.Parse((item.result_ok + item.result_error).ToString());
                    obj.accuracy = (int)(Math.Round(_result, 2) * 100);
                }
                obj.children = (len.Count > 0) ? GetAPPTeeModelById(list, item.folder_id) : null;
                listModel.Add(obj);
            }
            #endregion
            return listModel;
        }
        /// <summary>
        ///  递归获取文档树：统计
        /// </summary>
        /// <param name="list"></param>
        /// <param name="folder_id"></param>
        /// <returns></returns>
        private List<TreeDataStatisticsNode> GetAPPTeeModelById(List<TreeDataStatistics> list, int folder_id)
        {
            List<TreeDataStatisticsNode> listModel = new List<TreeDataStatisticsNode>();
            List<TreeDataStatistics> listKey = list.FindAll(s => s.folder_pid == folder_id)?.ToList();
            if (listKey.Count > 0)
            {
                foreach (TreeDataStatistics item in listKey)
                {
                    var len = list.Where(s => s.folder_pid == item.folder_id).ToList();
                    TreeDataStatisticsNode obj = new TreeDataStatisticsNode
                    {
                        folder_id = item.folder_id,
                        folder_pid = item.folder_pid,
                        learn_num = item.learn_num,
                        topic_num = item.topic_num,
                        result_ok = item.result_ok,
                        result_error = item.result_error
                    };
                    int allCount = item.result_ok + item.result_error;
                    if (item.result_error == 0 && allCount > 0)
                        obj.accuracy = 100;
                    else if (allCount > 0)
                    {
                        var _result = float.Parse(item.result_ok.ToString()) / float.Parse((item.result_ok + item.result_error).ToString());
                        obj.accuracy = (int)(Math.Round(_result, 2) * 100);
                    }
                    obj.children = (len.Count > 0) ? GetAPPTeeModelById(list, item.folder_id) : null;
                    listModel.Add(obj);
                }
            }
            else
                return null;
            return listModel;
        }
        /// <summary>
        ///  递归获取文档树
        /// </summary>
        /// <param name="list"></param>
        /// <param name="folder_id"></param>
        /// <returns></returns>
        private List<VRClientTreeModel> GetAPPModelById(EmpowerTree param, List<T_DocumentGoodFolder> list, int folder_id,int ply, string formatType = "tree")
        {
            List<VRClientTreeModel> listModel = new List<VRClientTreeModel>();
            List<T_DocumentGoodFolder> listKey = list.FindAll(s => s.folder_pid == folder_id)?.OrderByDescending(s => s.folder_order)?.ToList();
            if (listKey.Count > 0)
            {
                foreach (T_DocumentGoodFolder item in listKey)
                {
                    var len = list.Where(s => s.folder_pid == item.folder_id).ToList();
                    string folderName = item.folder_name;
                    int _ply = ply;
                    VRClientTreeModel treeTemp = new VRClientTreeModel
                    {
                        floor_level = item.floor_level,
                        city = item.city,
                        bs_url= item.bs_url,
                        addr = item.addr,
                        statr_partner = item.statr_partner,
                        create_name = item.create_name,
                        create_date = item.create_time.ToString("yyyy-MM-dd HH:mm"),
                        update_name = item.update_name,
                        update_date = item.update_date.ToString("yyyy-MM-dd HH:mm"),
                        ply = item.levels,
                        learn_num = item.learn_num,
                        topic_num = item.topic_num,
                        result_ok = item.result_ok,
                        result_error = item.result_error,
                        id = item.folder_id,
                        is_recommend = item.is_recommend,
                        name = folderName,
                        enLang = item.enLang,
                        pId = item.folder_pid,
                        materType = item.mater_type,
                        //if_create_child = item.if_create_child,
                        read_only = item.read_only,
                        //was_share = item.was_share,
                        //if_sys = item.if_sys,
                        folder_path = item.folder_path,
                        //doc_type = item.doc_type,
                        //pageType = item.page_type,
                        //rest_type = item.rest_type,
                        folder_note = item.folder_note,
                        unit_code = item.unit_code,
                        folder_order = (item.folder_order != null) ? (int)item.folder_order : 0,
                        folder_url = (!string.IsNullOrEmpty(item.folder_url)) ? item.folder_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) : "",
                        pro_type = item.pro_type,
                        proType = item.proType,
                        if_private = item.if_private?1:0,
                        //if_limit = item.if_limit,
                        group_name = item.group_name,
                        is_share = item.is_share ? 1 : 0,
                        favorite = item.favorite,
                        isFavorite = item.favorite > 0 ? true : false,
                        founder_id = item.founder_id,
                        founder_name = item.founder_name,
                        founder_phone = item.founder_phone,
                        sense = item.sense
                    };
                    //treeTemp.learn_num = DBSession.IT_VLinesExperienceDetailDAL.CountLearnNumByPath(item.folder_path);
                    //合伙人协议
                    var deal_note = DBSession.IT_VRFounderDealDAL.FindSingle(o => o.folder_id == item.folder_id);
                    treeTemp.deal_note = deal_note?.deal_note;
                    //判断用户是否点赞
                    if (param.user > 0)
                    {
                        int isStar = DBSession.IT_VRUserFolderStarDAL.SelectCount(s => s.user_guid.Equals(param.userid) && s.folder_id == item.folder_id);
                        treeTemp.isStar = isStar > 0;
                        treeTemp.star_num = isStar > 0 ? isStar : 0;
                        int isFous = DBSession.IT_VRUserFolderDAL.SelectCount(s => s.user_guid.Equals(param.userid) && s.folder_id == item.folder_id);
                        treeTemp.focus_num = isFous > 0 ? isFous : 0;
                    }
                    int allCount = item.result_ok + item.result_error;
                    if (item.result_error == 0 && allCount > 0)
                        treeTemp.accuracy = 100;
                    else if (allCount > 0)
                    {
                        var _result = float.Parse(item.result_ok.ToString()) / float.Parse((item.result_ok + item.result_error).ToString());
                        treeTemp.accuracy = (int)(Math.Round(_result, 2) * 100);
                    }
                    if (formatType.Equals("tree"))
                    {
                        treeTemp.children = (len.Count > 0) ? GetAPPModelById(param,list, item.folder_id, (++_ply)) : null;
                        listModel.Add(treeTemp);
                    }
                    else
                    {
                        listVRTreeModel.Add(treeTemp);
                        if (len.Count > 0)
                            GetAPPModelById(param,list, item.folder_id, (++_ply),formatType);
                    }
                }
            }
            else
                return null;
            return listModel;
        }
        #endregion
        private void SetFolderName(List<DocTreeModel> model)
        {
            foreach (DocTreeModel item in model)
            {
                var obj = docTempList.Where(s => s.folder_id == item.id).FirstOrDefault();
                if (obj != null && obj.total > 0)
                {
                    if (item.name.IndexOf("(") > -1)
                        item.name = item.name.Split('(')[0] + string.Format("({0})", obj.total);
                    else
                        item.name += string.Format("({0})", obj.total);
                }
                if (item.children != null)
                    SetFolderName(item.children);
            }
        }
        private int GetFolderName(List<DocTreeModel> listModel, List<DocTreeListModel> model, int folder_id,int doc_type)
        {
            int total = 0;
            foreach (DocTreeListModel item in model)
            {
                int ownCount = item.total, childCount = 0;
                var child = docList.Where(s => s.folder_pid == item.folder_id).ToList();
                if (child.Count > 0)
                    childCount += GetFolderName(listModel, child, item.folder_id,doc_type);
                total += ownCount + childCount;
                if (total > 0 && child.Count > 0)
                    docTempList.Add(new DocTreeListModel { folder_id = item.folder_id, total = total });
            }
            return total;
        }
        /// <summary>
        ///  递归获取文档树
        /// </summary>
        /// <param name="list"></param>
        /// <param name="folder_id"></param>
        /// <returns></returns>
        private List<DocTreeModel> GetModelById(List<T_DocumentFolder> list, int folder_id,int doc_type,int vrType)
        {
            List<DocTreeModel> listModel = new List<DocTreeModel>();
            List<T_DocumentFolder> listKey = list.FindAll(s => s.folder_pid == folder_id)?.OrderByDescending(s => s.folder_order)?.ToList();
            if (listKey.Count > 0)
            {
                foreach (T_DocumentFolder item in listKey)
                {
                    var len = list.Where(s => s.folder_pid == item.folder_id).ToList();
                    //统计商品数量
                    int total = GetFileInfoCount(doc_type, item.folder_id,item.folder_path,vrType);
                    //语言库对应翻译
                    var langName = LangHelper.GetValue("NavigationFolder." + item.langCode);
                    string folderName = (!string.IsNullOrEmpty(langName) && !langName.Equals("null")) ? langName : item.folder_name;
                    if(isCount && len.Count<=0 && total > 0)
                        folderName += total > 0 ? string.Format("({0})", total) : "";
                    docTempList.Add(new DocTreeListModel { folder_id = item.folder_id, folder_pid = item.folder_pid, total = total });
                    var parent = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == item.folder_pid);
                    listModel.Add(new DocTreeModel()
                    {
                        founder_id = item.founder_id,
                        founder_login = item.founder_login,
                        founder_name = item.founder_name,
                        id = item.folder_id,
                        name = folderName,
                        enLang = (!isChinese) ? folderName : item.enLang,
                        pId = item.folder_pid,
                        pName = parent?.folder_name,
                        pPath = parent?.folder_path,
                        materType = item.mater_type,
                        if_create_child = item.if_create_child,
                        read_only = item.read_only,
                        was_share = item.was_share,
                        if_sys = item.if_sys,
                        folder_path = item.folder_path,
                        doc_type = item.doc_type,
                        re_folder = item.is_recommend ? 1 : 0,
                        is_recommend = item.is_recommend,
                        //rest_type = item.rest_type,
                        folder_note = item.folder_note,
                        pro_type = item.pro_type,
                        unit_code = item.unit_code,
                        folder_order = (item.folder_order != null) ? (int)item.folder_order : 0,
                        if_private = item.if_private,
                        if_limit = item.if_limit,
                        group_name = item.group_name,
                        is_share = item.is_share ? 1 : 0,
                        gps_x = item.gps_x,
                        gps_y = item.gps_y,
                        bs_type = item.bs_type,
                        floor_level = item.floor_level,
                        city = item.city,
                        bs_url = item.bs_url,
                        addr = item.addr,
                        sortType = item.sortType,
                        statr_partner = item.statr_partner,
                        children = (len.Count > 0) ? GetModelById(list, item.folder_id, doc_type,vrType) : null
                    });
                }
            }
            else
                return null;
            return listModel;
        }
        /// <summary>
        ///  统计文档节点下的文档数量
        /// </summary>
        /// <param name="doc_type">节点类型</param>
        /// <param name="folder_id">节点ID</param>
        /// <returns></returns>
        private int GetFileInfoCount(int doc_type,int folder_id,string folder_path,int vrType)
        {
            int total = 0;
            int user_id = HCQ2UI_Helper.OperateContext.Current.Usr.user_id;
            var dal = DBSession.IT_DocumentInfoDAL;
            DocTableParamModel model = new DocTableParamModel { folder_id = folder_id, folder_path = folder_path, vrType = vrType };
            switch (doc_type)
            {
                case 1: total = dal.GetTableByOwnShareDocCount(model, user_id); break;//我的分享
                case 2: total = dal.GetTableShareByOwnDocCount(model, user_id);break;//分享文档
                case 3: total = dal.GetTablePublicDocCountByOwn(model, user_id,5); break;//公用5
                case 4: total = dal.GetTableRemoveDocCount(model, user_id); break;//回收站
                case 5: total = dal.GetTableApproveDocCount(model, user_id, HCQ2UI_Helper.OperateContext.Current.Usr.unit_code); break;//待审核1
                case 6: total = dal.GetTablePublicDocCountByOwn(model, user_id,3); break;//共享文档
                default: total = dal.GetTableByOwnDocCount(model, user_id); break;//我的文档
            }
            return total;
        }
        /// <summary>
        ///  添加节点
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddNode(DocTreeModel model)
        {
            if (null == model)
                return 0;
            T_DocumentFolder folder = new T_DocumentFolder
            {
                folder_name = model.name,
                enLang = model.enLang,
                langCode = HCQ2_Common.Helper.GetGuid,
                folder_pid = model.pId,
                group_name = model.group_name,
                is_share = model.is_share > 0 ? true : false,
                mater_type = model.materType,
                if_create_child = true,
                read_only = false,
                folder_order = model.folder_order,
                pro_type = model.pro_type,
                create_id = HCQ2UI_Helper.OperateContext.Current.Usr.user_id,
                create_name = HCQ2UI_Helper.OperateContext.Current.Usr.user_name,
                create_time = DateTime.Now,
                update_date = DateTime.Now,
                update_name = HCQ2UI_Helper.OperateContext.Current.Usr.user_name,
                page_type = model.pageType,
                unit_code = model.unit_code,
                have_child = false,
                if_private = model.if_private,
                if_limit = model.if_limit,
                folder_note = model.folder_note,
                rest_type = string.Empty,
                is_recommend = model.is_recommend
            };
            Add(folder);
            if (folder.folder_pid > 0)
                Modify(new T_DocumentFolder { have_child = true }, s => s.folder_id == folder.folder_pid, "have_child");
            AutoSetPermiss(folder);
            return folder.folder_id;
        }
        /// <summary>
        ///  编辑节点
        /// </summary>
        /// <param name="mdoel"></param>
        /// <returns></returns>
        public int EditNode(int id, string name,int proType,int folder_order,string group_name, int if_private, int if_limit,int is_share)
        {
            if (id==0 || string.IsNullOrEmpty(name))
                return 0;
            T_DocumentFolder folder = new T_DocumentFolder
            {
                folder_id = id,
                folder_name = name,
                folder_order = folder_order,
                pro_type = proType,
                group_name = group_name,
                if_private = if_private > 0 ? true : false,
                if_limit = if_limit > 0 ? true : false,
                is_share = is_share > 0 ? true : false,
                update_name = HCQ2UI_Helper.OperateContext.Current.Usr.user_name,
                update_date = DateTime.Now
            };
            return Modify(folder, s => s.folder_id == folder.folder_id, "folder_name", "pro_type", "folder_order", "group_name", "if_private", "if_limit", "is_share", "update_name", "update_date");
        }
        /// <summary>
        ///  删除节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteNode(T_DocumentFolder model,int id)
        {
            if (id <= 0 || model==null)
                return 0;
            var count = Select(s => s.folder_pid == model.folder_pid && s.folder_id != id);
            int mark = Delete(s => s.folder_id == id);
            if (mark > 0 && (count == null || count.Count == 0))
                Modify(new T_DocumentFolder { have_child = false }, s => s.folder_id == model.folder_pid, "have_child");
            return mark;
        }
        /// <summary>
        ///  获取子目录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<TreeTableAttribute> GetMenuDataByPid(int id, string type, string sm_code)
        {
            List<T_DocumentFolder> list = null;
            if (!string.IsNullOrEmpty(type) && type.Equals("own"))
                list = DBSession.IT_DocumentFolderDAL.Select<int>(s => s.folder_id == id && !s.if_remove,
                    s => (int)s.folder_order, true);
            else
            {
                if(string.IsNullOrEmpty(sm_code))
                    list = DBSession.IT_DocumentFolderDAL.Select<int>(s => s.folder_pid == id && s.if_sys == true && !s.if_remove,
                    s => (int)s.folder_order, true);
                else
                    list = DBSession.IT_DocumentFolderDAL.Select<int>(s => s.folder_pid == id && s.if_sys == true && !s.if_remove &&(s.page_type.Equals(sm_code) || string.IsNullOrEmpty(s.page_type)),
                    s => (int)s.folder_order, true);
            }               
            if (list.Count <= 0)
                return null;
            List<TreeTableAttribute> listTree = new List<TreeTableAttribute>();
            foreach (T_DocumentFolder item in list)
            {
                listTree.Add(new TreeTableAttribute()
                {
                    id = item.folder_id.ToString(),
                    name = item.folder_name,
                    pId = item.folder_pid.ToString(),
                    url = item.folder_url,
                    icon = item.folder_image,
                    hasChild = item.have_child
                });
            }
            return listTree;
        }
        //系统节点
        /// <summary>
        ///  添加系统节点
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public DocTreeModel AddSysNode(DocTreeModel folder)
        {
            if(null==folder || string.IsNullOrEmpty(folder.name))
                return null;
            T_DocumentFolder model = new T_DocumentFolder
            {
                city = folder.city,
                bs_url= folder.bs_url,
                addr = folder.addr,
                is_recommend = folder.re_folder > 0 ? true : false,
                gps_x = folder.gps_x,
                gps_y = folder.gps_y,
                bs_type = folder.bs_type,
                folder_name = folder.name,
                enLang = folder.enLang,
                langCode = Helper.GetGuid,
                pro_type = folder.pro_type,
                folder_pid = folder.pId,
                mater_type = folder.materType,
                was_share = folder.was_share,
                if_create_child = folder.if_create_child,
                read_only = folder.read_only,
                if_sys = folder.if_sys,
                doc_type = folder.doc_type,
                folder_order = folder.folder_order,
                if_private = folder.if_private,
                if_limit = folder.if_limit,
                create_id = HCQ2UI_Helper.OperateContext.Current.Usr.user_id,
                create_name = HCQ2UI_Helper.OperateContext.Current.Usr.user_name,
                create_time = DateTime.Now,
                update_date = DateTime.Now,
                update_name = HCQ2UI_Helper.OperateContext.Current.Usr.user_name,
                page_type = folder.pageType,
                have_child = false,
                unit_code = folder.unit_code,
                group_name = folder.group_name,
                rest_type = string.Empty,
                folder_note = folder.folder_note,
                statr_partner = folder.statr_partner,
                floor_level = !string.IsNullOrEmpty(folder.floor_level) ? folder.floor_level.Replace('，', ',').Trim(',') : "",
                is_share = folder.is_share > 0 ? true : false
            };
            if (folder.founder_id > 0)
            {
                model.founder_id = folder.founder_id;
                model.founder_name = folder.founder_name;
            }
            int mark = Add(model);
            if(folder.pId>0)
                Modify(new T_DocumentFolder { have_child = true }, s => s.folder_id == folder.pId, "have_child");
            if (mark > 0)
            {
                AutoSetPermiss(model);//自动设置权限
                folder.id = model.folder_id;
                //父目录信息
                var parent = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == folder.pId);
                folder.folder_path = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == folder.id)?.folder_path;
                folder.pName = parent?.folder_name;
                folder.pPath = parent?.folder_path;
                return folder;
            }
            return null;
        }
        /// <summary>
        ///  编辑系统节点
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public DocTreeModel EditSysNode(DocTreeModel folder)
        {
            if(null==folder || folder.id<=0 || string.IsNullOrEmpty(folder.name))
                return null;
            T_DocumentFolder model = new T_DocumentFolder
            {
                city = folder.city,
                bs_url = folder.bs_url,
                addr = folder.addr,
                is_recommend = folder.re_folder > 0 ? true : false,
                gps_x = folder.gps_x,
                gps_y = folder.gps_y,
                bs_type = folder.bs_type,
                folder_id = folder.id,
                mater_type = folder.materType,
                folder_name = folder.name,
                enLang = folder.enLang,
                folder_pid = folder.pId,
                was_share = folder.was_share,
                if_create_child = folder.if_create_child,
                read_only = folder.read_only,
                if_sys = folder.if_sys,
                folder_order = folder.folder_order,
                doc_type = folder.doc_type,
                pro_type = folder.pro_type,
                unit_code = folder.unit_code,
                if_private = folder.if_private,
                if_limit = folder.if_limit,
                group_name = folder.group_name,
                rest_type = string.Empty,
                folder_note = folder.folder_note,
                is_share = folder.is_share > 0 ? true : false,
                update_name = HCQ2UI_Helper.OperateContext.Current.Usr.user_name,
                update_date = DateTime.Now,
                founder_id = folder.founder_id,
                founder_name = folder.founder_name,
                founder_login = folder.founder_login,
                statr_partner = folder.statr_partner,
                floor_level = !string.IsNullOrEmpty(folder.floor_level) ? folder.floor_level.Replace('，', ',').Trim(',') : ""
            };
            int mark = Modify(model, s => s.folder_id == model.folder_id, "folder_name", "folder_pid", "enLang", "was_share", "if_create_child", "read_only", "if_sys", "doc_type", "folder_note", "pro_type", "unit_code", "folder_order", "if_private", "if_limit", "group_name", "mater_type", "is_recommend", "is_share", "update_name", "update_date", "founder_id", "founder_name", "founder_login", "gps_x", "gps_y", "bs_type", "statr_partner", "floor_level", "city", "addr");
            //父目录信息
            var parent = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == folder.pId);
            folder.folder_path = DBSession.IT_DocumentFolderDAL.FindSingle(s => s.folder_id == folder.id)?.folder_path;
            folder.pName = parent?.folder_name;
            folder.pPath = parent?.folder_path;
            return folder;
        }
        /// <summary>
        ///  判断是否需要设置目录权限
        /// </summary>
        /// <param name="model"></param>
        private void AutoSetPermiss(T_DocumentFolder model)
        {
            if (model.folder_pid <= 0)
                return;
            string sm_code = model.page_type;
            //添加成功：自动配置权限
            List<int> perList = DBSession.IT_PermissionsDAL.Select(s => s.per_type.Equals("docMenu") && s.sm_code.Equals(sm_code)).Select(s => s.per_id)?.ToList();
            if (perList != null && perList.Count > 0)
            {
                foreach (int per_id in perList)
                {
                    if (model.folder_pid <= 0)
                        DBSession.IT_DocFolderPermissRelationDAL.Add(new T_DocFolderPermissRelation { folder_id = model.folder_id, per_id = per_id });
                    else
                    {
                        int temp = DBSession.IT_DocFolderPermissRelationDAL.SelectCount(s => s.per_id == per_id && s.folder_id == model.folder_pid);
                        if (temp > 0)
                            DBSession.IT_DocFolderPermissRelationDAL.Add(new T_DocFolderPermissRelation { folder_id = model.folder_id, per_id = per_id });
                    }
                }
            }
        }
        /// <summary>
        ///  获取目录以及子目录下课件数量，判断是否允许删除目录
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public int GetFolderFileNum(string folderPath)
        {
            return DBSession.IT_DocumentFolderDAL.GetFolderFileNum(folderPath);
        }
        /// <summary>
        ///  获取目录详情
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultFolderDetials GetFoldersDetail(FolderDetialModel model, string folder_path)
        {
            ResultFolderDetials reslt = new ResultFolderDetials();
            List<FolderDetials> list= DBSession.IT_DocumentFolderDAL.GetFoldersDetail(model, folder_path);
            //处理原始数据
            list?.ForEach(s =>
            {
                //处理店铺角色列表
                if (!string.IsNullOrEmpty(s.store_type))
                    s.roleList = new List<string>(s.store_type.Split(','));
                if (model.create_id == s.founder_id)
                    s.partner_status = 100;
                else
                {
                    var pCount = DBSession.IT_VRFounderApplyDAL.FindSingle(o => o.folder_id == s.id && o.user_id == model.create_id);
                    if (pCount == null)
                        s.partner_status = -1;
                    else
                        s.partner_status = pCount.apply_status;
                }
                if (s.dealId != null)
                    s.deal_url = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")) + $"/uploadFile/FouderPact/FouderPact.html?id={s.dealId}";
            });
            //一级目录
            var folder = list.Where(s => s.id == model.folder_id).FirstOrDefault();
            reslt = folder.ToFolderDetials();
            List<ResultFolderDetials> children = new List<ResultFolderDetials>();
            //二级及以下
            var folders = list.Where(s => s.pId == folder.id)?.ToList();
            folders?.ForEach(s =>
            {
                ResultFolderDetials temp = s.ToFolderDetials();
                if (temp.have_child)
                    temp.children = GetChildrenFolder(list, s.id);
                children.Add(temp);
                reslt.children = children;
            });
            return reslt;
        }

        private List<ResultFolderDetials> GetChildrenFolder(List<FolderDetials> list,int folder_id)
        {
            List<ResultFolderDetials> children = new List<ResultFolderDetials>();
            var folders = list.Where(s => s.pId == folder_id)?.ToList();
            folders?.ForEach(s=> {
                ResultFolderDetials temp = s.ToFolderDetials();
                if (s.have_child)
                    temp.children = GetChildrenFolder(list, s.id);
                children.Add(temp);
            });
            return children;
        }

        /// <summary>
        ///  获取用户收藏目录列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<CollectFolderResult> GetUserFolderCollectList(CollectFolderList model)
        {
            //获取数据集合
            List<FolderResult> folders = DBSession.IT_DocumentFolderDAL.GetUserFolderCollectList(model);
            List<CollectFolderResult> list = new List<CollectFolderResult>();
            if (folders == null || folders.Count <= 0)
                return null;
            //整合父子目录
            if (folders.Count <= 0)
                return null;
            //第一层目录
            var query = folders.Where(s => s.pid == 0).ToList();
            query.ForEach(s =>
            {
                list.Add(new CollectFolderResult
                {
                    folder_id=s.folder_id,
                    folder_name = s.folder_name,
                    folder_note = s.folder_note,
                    folder_url = s.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))),
                    child = GetChildFolder(folders, s.folder_id)
                });
            });
            return list;
        }

        private List<CollectFolderResult> GetChildFolder(List<FolderResult> folders,int folder_id)
        {
            List<CollectFolderResult> list = new List<CollectFolderResult>();
            var query = folders.Where(s => s.folder_pid == folder_id).ToList();
            if (query.Count <= 0)
                return null;
            query.ForEach(s =>
            {
                list.Add(new CollectFolderResult
                {
                    folder_id = s.folder_id,
                    folder_name = s.folder_name,
                    folder_note = s.folder_note,
                    folder_url = s.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))),
                    child = GetChildFolder(folders, s.folder_id)
                });
            });
            return list;
        }
        /// <summary>
        ///  获取用户权限内可看目录
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<T_DocumentFolder> GetUserFolderPermiss(int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetUserFolderPermiss(user_id);
        }
        /// <summary>
        ///  获取用户关注目录排行
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<UserFolderRank> GetUserStarFolderRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetUserStarFolderRank(param, user_id);
        }
        /// <summary>
        ///  获取用户关注作品排行
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<UserWorkStar> GetUserStarWorkRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetUserStarWorkRank(param, user_id);
        }
        /// <summary>
        ///  获取作品下载排行
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<UserWorkStar> GetWorkDownloadRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetWorkDownloadRank(param, user_id);
        }
        /// <summary>
        ///  获取作品学习排行
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<UserWorkStar> GetWorkLearnRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetWorkLearnRank(param, user_id);
        }
        /// <summary>
        ///  获取用户学习排行
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<UserLearnRank> GetUserLearnRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetUserLearnRank(param, user_id);
        }
        /// <summary>
        ///  获取用户答题正确率
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<UserAccuracyRank> GetUserOkAccuracyRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetUserOkAccuracyRank(param, user_id);
        }
        /// <summary>
        ///  获取错题目排行
        /// </summary>
        /// <param name="param"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<LinesErrorRank> GetLinesErrorRank(FavoriteRankParam param, int user_id)
        {
            return DBSession.IT_DocumentFolderDAL.GetLinesErrorRank(param, user_id);
        }
        /// <summary>
        ///  验证pid是否属于folder_path的只目录
        /// </summary>
        /// <param name="fodler_path"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public int CheckParentTree(string folder_path, int pid)
        {
            return DBSession.IT_DocumentFolderDAL.CheckParentTree(folder_path, pid);
        }
        /// <summary>
        ///  判断当前目录下是否有子目录
        /// </summary>
        /// <param name="folder_path"></param>
        /// <returns></returns>
        public int CheckIsChild(string folder_path)
        {
            return DBSession.IT_DocumentFolderDAL.CheckIsChild(folder_path);
        }
        /// <summary>
        ///  判断当前目录是否有课件
        /// </summary>
        /// <param name="folder_id"></param>
        /// <returns></returns>
        public int CheckIsWorks(int folder_id)
        {
            return DBSession.IT_DocumentFolderDAL.CheckIsWorks(folder_id);
        }

        /// <summary>
        ///  获取作品数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int GetWorkNum(WorkNumInputDto dto)
        {
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(dto.userid);
            List<string> list = DBSession.IT_DocumentFolderDAL.GetFolderPathByIds(dto.folderId);
            return DBSession.IT_DocumentFolderDAL.GetWorkNum(dto,user_id, list);
        }
        /// <summary>
        ///  获取目录数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int GetFolderNum(FolderNumInputDto dto)
        {
            //1.获取当前用户权限集合
            List<int> pList = new List<int>();
            if (dto.user_id > 0)
            {
                List<T_Permissions> PerList = DBSession.IT_PermissionsDAL.GetPermissById(dto.user_id);
                if (PerList != null && PerList.Count > 0)
                    pList = PerList.Select(s => s.per_id).ToList();
            }
            return DBSession.IT_DocumentFolderDAL.GetFolderNum(dto, pList);
        }
        /// <summary>
        ///  获取上课人数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int GetLearnNum(LearnClassNumInputDto dto)
        {
            return DBSession.IT_DocumentFolderDAL.GetLearnNum(dto);
        }
        /// <summary>
        ///  获取直播课堂数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int GetLinesClassNum(LearnClassNumInputDto dto)
        {
            //1.获取当前用户权限集合
            List<int> pList = new List<int>();
            if (dto.user_id > 0)
            {
                List<T_Permissions> PerList = DBSession.IT_PermissionsDAL.GetPermissById(dto.user_id);
                if (PerList != null && PerList.Count > 0)
                    pList = PerList.Select(s => s.per_id).ToList();
            }
            return DBSession.IT_DocumentFolderDAL.GetLinesClassNum(dto, pList);
        }
        /// <summary>
        ///  获取我的店铺
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<MyFloderModel> GetMyFloderList(MyFloderParam param, int user_id)
        {
            var list = DBSession.IT_DocumentFolderDAL.GetMyFloderList(param, user_id);
            list?.ForEach(s =>
            {
                //处理店铺角色列表
                if (!string.IsNullOrEmpty(s.store_type))
                    s.roleList = new List<string>(s.store_type.Split(','));
                //处理合伙人状态
                if (user_id == s.founderID)
                    s.partnerStatus = 100;
                else
                {
                    var pCount = DBSession.IT_VRFounderApplyDAL.FindSingle(o => o.folder_id == s.folder_id && o.user_id == user_id);
                    if (pCount == null)
                        s.partnerStatus = -1;
                    else
                        s.partnerStatus = pCount.apply_status;
                }
                if (!string.IsNullOrEmpty(s.folder_url))
                    s.folder_url = s.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                //商品列表
                var file= DBSession.IT_DocumentFolderDAL.GetGoodsByFolders(s.folder_path,param.fileListNum);
                file?.ForEach(o=> {
                    if (!string.IsNullOrEmpty(o.fileImage))
                        o.fileImage = o.fileImage?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                });
                s.fileList = file;
            });
            return list;
        }
        /// <summary>
        ///  获取所有店铺
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<MyFloderModel> GetAllFloderList(AllFloderParam param,int user_id)
        {
            var list = DBSession.IT_DocumentFolderDAL.GetAllFloderList(param,user_id);
            list?.ForEach(s =>
            {
                //处理店铺角色列表
                if (!string.IsNullOrEmpty(s.store_type))
                    s.roleList = new List<string>(s.store_type.Split(','));
                //处理合伙人状态
                if (user_id == s.founderID)
                    s.partnerStatus = 100;
                else
                {
                    var pCount = DBSession.IT_VRFounderApplyDAL.FindSingle(o => o.folder_id == s.folder_id && o.user_id == user_id);
                    if (pCount == null)
                        s.partnerStatus = -1;
                    else
                        s.partnerStatus = pCount.apply_status;
                }
                if (!string.IsNullOrEmpty(s.folder_url))
                    s.folder_url = s.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                //商品列表
                var file = DBSession.IT_DocumentFolderDAL.GetGoodsByFolders(s.folder_path,param.fileListNum);
                file?.ForEach(o => {
                    if (!string.IsNullOrEmpty(o.fileImage))
                        o.fileImage = o.fileImage?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                });
                s.fileList = file;
            });
            return list;
        }
        /// <summary>
        ///  获取我的课程（目录）列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<OutputMyCourse> GetMyCourseList(MyCourseParam param, int user_id)
        {
            List<OutputMyCourse> result = new List<OutputMyCourse>();
            var list = DBSession.IT_DocumentFolderDAL.GetMyCourseList(param, user_id);
            if (list == null || list.Count <= 0)
                return result;
            list?.ForEach(s =>
            {
                OutputMyCourse temp = s.ToOutputMyCourse();
                if (!string.IsNullOrEmpty(temp.folder_url))
                    temp.folder_url = temp.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                if (temp.ok_num > 0 && temp.error_num <= 0)
                    temp.record_rate = 100;
                else  if (temp.ok_num <= 0)
                    temp.record_rate = 0;
                else if(temp.error_num <= 0)
                    temp.record_rate = 100;
                else
                {
                    //计算
                    decimal all = Helper.ToDecimal(temp.ok_num + temp.error_num);
                    temp.record_rate = Math.Round(temp.ok_num / all, 2) * 100;
                }
                //课程最近更新作品
                List<ModifyGoodList> m = DBSession.IT_DocumentFolderDAL.GetMyModifyGoodList(s.folder_path);
                m?.ForEach(n =>
                {
                    List<T_DocBagFileRecord> photoOption = DBSession.IT_DocBagFileRecordDAL.Select(i => i.file_id == n.file_id);
                    if (photoOption.Count > 0)
                        photoOption.ForEach(o => o.file_url = o.file_url.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))));
                    n.photoOption = photoOption;
                });
                temp.editList = m;
                result.Add(temp);
            });
            return result;
        }

    }
}